<template>
  <div style="background-color: #f5f5f5; padding: 0px; min-height: 100vh; display: flex; justify-content: center; align-items: flex-start;">
    <!-- 模仿纸张的容器 -->
    <div
        style="background-color: #ffffff; width: 1100px; min-height: calc(100vh - 40px); margin-top: 50px; padding: 40px 20px; border-radius: 8px; box-shadow: 0 6px 12px rgba(0, 0, 0, 0.1); border: 1px solid #e0e0e0; display: flex; position: relative;"
    >
      <!-- 内容区域 -->
      <div style="flex: 1; padding: 0 20px; font-size: 0.95rem; overflow-y: auto;">
        <div v-html="content" ref="content" style="padding: 40px;"></div>
      </div>

      <!-- 目录区域 -->
      <div style="width: 250px; padding: 20px; border-left: 1px solid #e0e0e0; overflow-y: auto; position: sticky; top: 0;">
        <!-- 编辑按钮 -->
        <el-tooltip content="编辑" placement="bottom">
          <el-button  @click="editAdd()"  type="primary" icon="el-icon-edit" plain circle style="margin-left: 10px; padding: 15px 15px; border: none; cursor: pointer;"></el-button>
        </el-tooltip>
        <!-- 收藏按钮 -->
        <el-tooltip content="收藏" placement="bottom">
          <el-button @click="favoriteAdd()" type="warning" icon="el-icon-star-off" plain circle style="margin-left: 10px; padding: 15px 15px; border: none; cursor: pointer;"></el-button>
        </el-tooltip>
        <!-- 转发按钮 -->
        <el-tooltip content="转发" placement="bottom">
          <el-button type="success" icon="el-icon-position" plain circle style="margin-left: 10px; padding: 15px 15px; border: none; cursor: pointer;"></el-button>
        </el-tooltip>
        <!-- 删除按钮 -->
        <el-tooltip content="删除" placement="bottom">
          <el-button    @click="deleteNote()" type="danger" icon="el-icon-delete" plain circle style="margin-left: 10px; padding: 15px 15px; border: none; cursor: pointer;"></el-button>
        </el-tooltip>
        <h3>目录</h3>
        <ul style="color: #757575;">
          <li
              v-for="(item, index) in toc"
              :key="index"
              :style="{ marginLeft: item.level * 10 + 'px' }"
          >
            <a href="#" @click.prevent="scrollToAnchor(item.id)" style="color: inherit; text-decoration: none;">{{ item.text }}</a>
          </li>
        </ul>
      </div>
    </div>

    <el-dialog title="编辑笔记" top="0.51vh" modal="true"   :visible.sync="editFormVisble" width="40%" height="'auto'"  @close="closeDialog":close-on-click-modal="false">
      <el-form :model="editForm" label-width="80px" style="padding-right: 20px" :rules="rules" ref="formRef">
        <el-form-item label="标题" prop="title">
          <el-input v-model="editForm.title" placeholder="标题"  ></el-input>
        </el-form-item>
        <el-form-item label="简介" prop="descr">
          <el-input v-model="editForm.descr" placeholder="简介"> </el-input>
        </el-form-item>
        <el-form-item label="内容"  prop="content">
          <div  id="edit-editor"></div>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="editFormVisble = false">取 消</el-button>
        <el-button type="primary" @click="edit">确 定</el-button>
      </div>
    </el-dialog>
  </div>

</template>

<script>
import E from "wangeditor";
import hljs from "highlight.js";

export default {
  name: "Note",
  data() {
    return {
      noteId: null,
      noteName: '',
      content: '', // 动态 HTML 内容
      toc: [], // 目录数据
      editFormVisble:false,
      editForm: {
        title: '',
        descr: '',
        content: '',
        userId:'',
        categoryBy:""
      },
      favoriteForm:{
        noteId:'',
        userId:''
      },
      user: JSON.parse(localStorage.getItem('honey-user') || '{}'),
      editor: null,
      query: {
        id: null,
        name: '',
        content: '',
      },
      deleteInfo:{
        id:'',
        userId:''
      },
    };
  },
  created() {
    this.updateNoteData();
  },
  mounted() {
    this.generateTOC();
  },
  methods: {
    closeDialog(){
      // 销毁编辑器
      this.editor.destroy()
      this.editor = null
    },
    favoriteAdd(){
      this.favoriteForm.noteId = this.query.id
      this.favoriteForm.userId = this.user.userId
      this.$request({
        url: '/favorites/add',
        method: 'POST',
        data: this.favoriteForm
      }).then(res => {
        if (res.code === "200") {//表示成功保存
          this.$message.success('收藏成功')
        } else {
          this.$message.error(res.msg)//弹出错误信息
        }
      })
    },
    editAdd() {
      this.editFormVisble = true; //打开弹窗
      this.editForm.title = this.query.name;
      this.editForm.id=this.query.id
      this.editForm.descr = this.query.descr;
      this.editForm.userId=this.user.userId
      this.setRichText();
      setTimeout(()=>{
        this.editor.txt.html(this.query.content)   // 获取内容
      },0);
    },
    edit(){
      this.$refs.formRef.validate((valid) => {
        console.log(valid)
        if (valid) {
          //获取编辑框的内容
          let content = this.editor.txt.html()   // 设置html
          this.editForm.content=content
          this.$request({
            url: '/notes/edit',
            method: 'POST',
            data: this.editForm
          }).then(res => {
            if (res.code === "200") {//表示成功保存
              this.$message.success('编辑成功')
              this.editFormVisble = false;
            } else {
              this.$message.error(res.msg)//弹出错误信息
            }
          })
        }
      })

    },
    setRichText(){
      this.$nextTick(()=>{
        this.editor = new E(`#edit-editor`)
        this.editor.highlight = hljs
        this.editor.config.placeholder = '请输入内容...'
        this.editor.config.uploadImgServer = this.$baseUrl + '/file/upload'
        this.editor.config.uploadFileName = 'file'
        this.editor.config.uploadImgHeaders = {
          'x-token': this.user.token
        }
        this.editor.config.timeout= 5000*2
        this.editor.config.uploadImgParams={
          type:'img'
        }
        this.editor.config.height = 550; // 设置高度
        //  this.editor.config.width = 300; // 设置宽度
        // 自定义图片上传逻辑

        this.editor.config.uploadImgMaxSize = 40 * 1024 * 1024 // 10M
        this.editor.config.uploadVideoServer = this.$baseUrl + '/file/upload'
        this.editor.config.uploadVideoName = 'file'
        // this.editor.config.uploadVideoHeaders = {
        //     token: this.user.token
        // }
        this.editor.config.uploadVideoParams={
          type:'video'
        }
        this.editor.config.maxFileSize= 200 * 1024 * 1024, // 200M
            this.editor.config.allowedFileTypes=['mp4','MP4'],
            this.editor.create()  // 创建
      })
    },
    deleteNote() {
      if (!this.query.id || !this.user.userId) {
        this.$message.error("缺少必要的删除参数");
        return;
      }
      this.$confirm('此操作将永久删除该文件, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      }).then(() => {
            const deleteParams = {
              id: this.query.id,
              userId: this.user.userId,
            };

            this.$request.post('/notes/delete', deleteParams)
                .then((res) => {
                  if (res.code === "200") {
                    this.$message.success("删除成功");
                    this.toIndex();
                  } else {
                    this.$message.error(res.message || "删除失败");
                  }
                })
                .catch((err) => {
                  console.error("删除请求失败:", err);
                  this.$message.error(err?.response?.data?.message || "删除请求失败，请重试");
                });
          })
          .catch(() => {
            this.$message({
              type: 'info',
              message: '已取消删除',
            });
          });
    },

    toIndex() {
      const currentId = this.$route.query.id; // Current id in the route
      const storedId = localStorage.getItem('noteListId');
      if (storedId !== currentId) { // Only replace if ids are different
        this.$router.replace({
          path: '/noteList',
          query: { id: storedId }
        });
      }
    },

    updateNoteData() {
      this.query = this.$route.query;
      this.noteId = this.query.id;
      this.noteName =  this.query.name;
      this.content =  this.query.content;
      this.$nextTick(() => this.generateTOC()); // 重新生成目录

    },
    generateTOC() {
      const contentEl = this.$refs.content; // 获取内容 DOM
      if (!contentEl) return;

      const headers = contentEl.querySelectorAll("h1, h2, h3"); // 仅提取 h1, h2, h3
      const toc = [];

      headers.forEach((header, index) => {
        const level = parseInt(header.tagName[1], 10); // 获取级别
        const text = header.innerText; // 获取标题文本
        const id = header.id || `header-${index}`; // 确保每个标题有唯一的 ID
        header.id = id; // 设置 ID 到 DOM
        toc.push({ level, text, id });
      });

      this.toc = toc; // 更新目录数据
    },
    scrollToAnchor(id) {
      const target = document.getElementById(id); // 查找目标 DOM
      if (target) {
        target.scrollIntoView({ behavior: "smooth", block: "start" }); // 平滑滚动
      }
    },
  },
  watch: {
    '$route.query': 'updateNoteData', // 监听路由变化
  },
};
</script>

<style scoped>
ul {
  list-style: none;
  padding: 0;
}

li {
  margin: 5px 0;
  font-size: 1rem; /* 默认字体大小 */
}

li a {
  color: inherit;
  text-decoration: none;
}

/* 添加新样式 - 目录列表项下面字体大小增大 */
li::after {
  content: "";
  display: block;
  border-bottom: 1px solid #e0e0e0;
  margin-top: 4px;
  margin-bottom: 8px;
}

li span {
  font-size: 1.1rem; /* 增大字体大小 */
}
#edit-editor {
  height: 590px; /* 确保编辑器有高度 */
}

</style>
